<?php

namespace App\HttpController\Admin;

use App\HttpController\BaseController;
use App\Model\AdminsModel;
use App\Model\LoginLogsModel;
use App\Utility\ApiToken;
use App\Utility\Captcha;
use Carbon\Carbon;
use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\Validate\Validate;


class LoginController extends BaseController {

    /**
     * @title 用户登录
     * @description 登录表单提交
     * @method POST
     * @request manage/login
     * @param string username 管理员账户 true ''
     * @param string password 密码 true ''
     * @param string captcha 验证码 true ''
     * @param string captchaKey 验证码key true ''
     * @return int userinfo.id 管理员id
     * @return string userinfo.nickname 管理员昵称
     * @return string redirect 成功跳转地址
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function login(){
        $request = $this->request();
        $data = $request->getRequestParam();

        // TODO: 字段验证.
        $validate = new Validate();
        // TODO: 字段验证闭包函数func只能返回true和false.
        $validateCode = (new Captcha())->check($data['captcha'],$data['captchaKey']);
        $validate->addColumn('captcha')->required('请填写验证码')->func(function () use($validateCode){
            return $validateCode;
        },'验证码输入错误');

        $adminModel = new AdminsModel();
        $user = $adminModel->where('username', $data['username'])->first();

        $validate->addColumn('username')->required('请填写管理员账号')->func(function () use($data,$user){
            return !empty($user);
        },'管理员账户不存在，请联系超级管理员');

        $validate->addColumn('password')->required('请填写密码')->func(function () use($data,$user){
            return password_verify($data['password'],$user['password']);
        },'密码输入错误');

        // TODO: 通过验证,登录用户信息存入session.返回用户信息和跳转链接.
        $loginLogModel = new LoginLogsModel();
        if($this->validate($validate)){
            $token = (new ApiToken())->sessionEncrypt(1);
            $return = [
                'userinfo' => ['id' => $user['id'], 'nickname' => $user['nickname']],
                'token' => $token
            ];
            // TODO: 记录成功登录日志
            $loginLogModel->createLog($data,$this->getIp(),1);
            return $this->writeJson(0,$return,'登录成功，页面即将跳转...');
        } else {
            // TODO: 记录失败登录日志
            $loginLogModel->createLog($data,$this->getIp(),0);
            return $this->writeJson(1, null, $validate->getError()->__toString());
        }
    }


    /**
     * @title 验证码
     * @description 获取验证码信息
     * @method GET
     * @request manage/captcha
     * @return string captcha 验证码图片地址
     * @return string captchaKey 验证码加密key,用于验证验证码是否正确
     */
    public function captcha(){
        $captcha = (new Captcha())->create();
        return $this->writeJson(0,$captcha);
    }
}
